<template>
  <div class="app-container">
    <div class="back-item">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="品类名" prop="categoryName" >
          <el-input
            v-model="queryParams.categoryName"
            placeholder="请输入品类名"
            clearable
            size="small"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="warning" icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button size="mini" @click="changSearch">{{showSearch?"常用条件":"所有条件"}}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="back-item">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['mall:category:add']"
          >新增</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="categoryList"
        row-key="categoryId"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column label="品类级别" align="center" width="100" prop="categoryType" v-if="columns[4].visible" >
          <template #default="scope">
            {{scope.row.categoryType==1?"一级":scope.row.categoryType==2?"二级":scope.row.categoryType==3?"三级":"-"}}
          </template>
        </el-table-column>
        <el-table-column label="品类名" prop="categoryName" v-if="columns[1].visible" />

        <el-table-column label="品类图片" align="center" prop="categoryImg" v-if="columns[2].visible" >
          <template #default="scope">
            <el-image :src="scope.row.categoryImg" style="width: 80px"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" v-if="columns[5].visible" />
        <el-table-column label="佣金比例" align="center" prop="chargeRate" v-if="columns[6].visible" />
        <el-table-column label="状态" align="center" prop="status" v-if="columns[7].visible" >
          <template #default="scope">
            {{scope.row.status==0?"禁用":scope.row.status==1?"正常":"-"}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" v-if="columns[8].visible">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mall:category:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="Plus"
              @click="handleAdd(scope.row)"
              v-if="scope.row.categoryType<3"
              v-hasPermi="['mall:category:add']"
            >新增</el-button>
            <el-button
              size="mini"
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['mall:category:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加或修改品类信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categoryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级品类" prop="parentId">
          <tree-select
            v-model:value="form.parentId"
            :options="fatherList"
            :objMap="{ value: 'categoryId', label: 'categoryName', children: 'children', type:'categoryType' }"
            @change="treeChange"
            placeholder="请选择父级ID"
          />
        </el-form-item>
        <el-form-item label="品类名" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入品类名" />
        </el-form-item>
        <el-form-item label="品类级别" prop="categoryType">
          {{form.categoryType==1?"一级":form.categoryType==2?"二级":form.categoryType==3?"三级":"-"}}
        </el-form-item>
        <el-form-item label="品类图片" prop="categoryImg">
          <!--<el-input v-model="form.categoryImg" placeholder="请输入品类图片" />-->
          <img-upload v-model="form.categoryImg" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
        </el-form-item>
        <!--<el-form-item label="佣金比例" prop="chargeRate">
          <el-input v-model="form.chargeRate" type="number" placeholder="请输入佣金比例" />
        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Category">
import { listCategory, treeListCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/mall/category";
import imgUpload from "@/components/upload/imgUpload";

const { proxy } = getCurrentInstance();

const categoryList = ref([]);
const fatherList = ref([]);
const categoryOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const title = ref("");

const data = reactive({
  // 列信息
  columns: [
    {key: 0, label: `品类ID`, visible: true},
    {key: 1, label: `品类名`, visible: true},
    {key: 2, label: `品类图片`, visible: true},
    {key: 3, label: `父级ID`, visible: true},
    {key: 4, label: `类型（ 1一级 2二级 3三级）`, visible: true},
    {key: 5, label: `排序`, visible: true},
    {key: 6, label: `佣金比例`, visible: true},
    {key: 7, label: `状态（ 0启用 1停用）`, visible: true},
    {key: 8, label: `操作`, visible: true},
  ],
  // 表单参数
  form: {},
  // 查询参数
  queryParams: {
    categoryName: null,
    categoryImg: null,
    parentId: null,
    categoryType: null,
    sort: null,
    chargeRate: null,
    status: null,
  },
  rules: {
  }
});

const { queryParams, form, rules, columns } = toRefs(data);

/** 查询品类信息列表 */
function getList() {
  loading.value = true;
  listCategory(queryParams.value).then(response => {
    categoryList.value = proxy.handleTree(response.data, "categoryId", "parentId");
    loading.value = false;
  });
  treeListCategory().then(response => {
    fatherList.value = filterThird(response.data)
    console.log(fatherList);
  })

}

/**过滤三级品类 */

function filterThird(treeList){
  let objList = treeList.map(item => {
    if (item.categoryType == 2){
      item.children = null;
    }else {
      filterThird(item.children)
    }
    return item;
  })
  return objList;
}

function treeChange(e){
  console.log(e);
  form.value.categoryType = String(Number(e) + 1);
}

/** 查询品类信息下拉树结构 */
async function getTreeselect() {
  await listCategory().then(response => {
    categoryOptions.value = [];
    const data = { categoryId: 0, categoryType: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "categoryId", "parentId");
    categoryOptions.value.push(data);
    console.log(categoryOptions.value);
  });
}
	
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    categoryId: null,
    categoryName: null,
    categoryImg: null,
    parentId: null,
    categoryType: null,
    sort: null,
    chargeRate: null,
    status: "0",

    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null
  };
  proxy.resetForm("categoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 切换按钮操作 */
function changSearch() {
  showSearch.value = !showSearch.value;
}
/** 新增按钮操作 */
async function handleAdd(row) {
  reset();
  await getTreeselect();
  if (row != null && row.categoryId) {
    form.value.parentId = row.categoryId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加品类信息";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.categoryId;
  }
  getCategory(row.categoryId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改品类信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryRef"].validate(valid => {
    if (valid) {
      if (form.value.categoryId != null) {
        updateCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除品类信息编号为"' + row.categoryId + '"的数据项？').then(function() {
    return delCategory(row.categoryId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();
</script>
